//
//  ShoppingCartListCtr-ext.swift
//  smosky
//
//  Created by zhuxietong on 2018/6/28.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import UIKit
import Eelay
import soapp
private let numKey = "total"


extension ShoppingCartListCtr{
    class SubmitBar:JoView{
        let priceL = UILabel()
        let confirmBt = UIButton()
        let contentView = UIView()
        
        override func addLayoutRules() {
            let line = UIView()
            self.eelay = [
                [contentView,[ee.B.safe],[ee.T.L.R],"45"]
            ]
            contentView.eelay = [
                [line,[ee.T.L.R],"0.4"],
                [confirmBt,[ee.T.B.R],150],
                [priceL,[confirmBt,ee.L,ee.R,-30],[ee.L,AppTheme.edge.+1000],[ee.Y]],
            ]
            line.backgroundColor = UIColor._separator
            
            let submitName = "提交订单".loc
            _ = confirmBt.ui.ncolor(hex: "#fff").font(size: 14).ntitle(title: submitName)
            //            confirmBt.contentEdgeInsets = [8,16]
            confirmBt.setBackgroundImage(UIImage(named: "shop_buy"), for: .normal)
            priceL.attributedText = "\("合计".loc)：".ui.font16.color(hex: "#111").astring + "¥\(0)".ui.color(hex: UIColor.main_hex).font16.astring
            backgroundColor = ._background
        }
        
        override var intrinsicContentSize: CGSize{
            get{
                return [Swidth,80]
            }
        }
        
        override func mo_model_reload() {
            
            let price = mo.model[float:"totalprice",0]
            priceL.attributedText = "\("合计".loc)：".ui.font16.color(hex: "#111").astring + "¥\(price.price_display)".ui.color(color: ___shop.tint).font16.astring
            
        }
        
    }
    
    class SellerCell: JoTableCell {
        let iconV = UIImageView()
        let nameL = UILabel()
        override func addLayoutRules() {
            let line = UIView()
            contentView.eelay = [
                [line,[ee.T.L.R],"6"],
                [iconV,[ee.T.L.B,[20,AppTheme.edge,-14]],"18",18],
                [nameL,[iconV,ee.R.Y,ee.L.Y,[10,0]],[ee.R,-AppTheme.edge]],
                [__line,[ee.L.B.R],"\(TP.separatorHeight)"]
            ]
            line.backgroundColor = ._tableBackground
            __line.backgroundColor = UIColor._separator
            _ = nameL.ui.font12.text(color: .color(light: "#444", dark: "#aaa")).left
        }
        
        override func mo_model_reload() {
            var model = mo.model
            if let dict = DataNode<NSMutableDictionary>.path(node: "__model", mo.model)
            {
                model = dict
            }
            iconV.img_url = model["logo",""]
            nameL.text = model["merchname",""]
        }
    }
    
    class SellerCell1: SellerCell {
        override func addLayoutRules() {
            let line = UIView()
            contentView.eelay = [
                [iconV,[ee.T.L.B,[14,AppTheme.edge,-4]],"18",18],
                [nameL,[iconV,ee.R.Y,ee.L.Y,[10,0]],[ee.R,-AppTheme.edge]],
            ]
            line.backgroundColor = UIColor.table_bg_color
            __line.backgroundColor = UIColor._separator
            _ = nameL.ui.font12.text(color: ._foregroundWeak).left
        }
        
        
    }
    
    class GoodsItemCell: JoTableCell {
        let imgV = UIImageView()
        let titleL = UILabel()
        let tagsL = UILabel()
        let priceL = UILabel()
        let selectedBt = UIButton()
        
        
        let deleteBt = UIButton()
        let disValidView = UIView()
        
        let numControl = NumStepControl()
        
        
        
        let disValidIndicator = UIImageView()
        override func addLayoutRules() {
            contentView.eelay = [
                [disValidView,[ee.T.L.B.R]],
                [selectedBt,[ee.Y.L,[0,AppTheme.edge]],"20",20],
                [imgV,[selectedBt,ee.R,ee.L,12],[ee.T.B,[12,-12]],"74",74],
                [titleL,[imgV,ee.R,ee.L,8],[imgV,ee.T,4],[ee.R,-100]],
                [tagsL,[imgV,ee.R,ee.L,8],[imgV,ee.B,-4],[ee.R,-AppTheme.edge]],
                [priceL,[imgV,ee.R.Y,ee.L.Y,[8,0]]],
                [__line,[ee.L.B.R,[0,0.0]],"0.4"],
                [numControl,[ee.R,-16],[titleL,ee.Y]],
                [disValidIndicator,[imgV,ee.T.L],"40",37]
            ]
            
            disValidView.eelay = [
                [deleteBt,[ee.R,-16],[ee.T,14]],
            ]
            deleteBt.ui.padding(insets: [3,8]).ncolor(color: ._foreground).ntitle(title: "删除".loc).font(size: 12).set(radius: 4, width: 1, color: UIColor(shex: "#999"))
            deleteBt.addTarget(self, action: #selector(deleteInvalid), for: .touchUpInside)
            
            
            selectedBt.setImage(UIImage(named:"radio_check_n"), for: .normal)
            selectedBt.setImage(UIImage(named:"radio_check_s"), for: .selected)
            disValidIndicator.image = UIImage(named: "shixiao")
            
            __line.backgroundColor = FieldCell.separator_color
            imgV.img_url = __goods.one_str
            titleL.ui.font12.text(color: ._foreground).text(__goodsNames.one_str)
            tagsL.ui.font11.text(color: ._foregroundWeak).text("颜色：黑")
            selectedBt.addTarget(self, action: #selector(toggle), for: .touchUpInside)
            
            imgV.isUserInteractionEnabled  = true
            let tap = UITapGestureRecognizer(target: self, action: #selector(openDetail))
            imgV.addGestureRecognizer(tap)
            
            weak var wself = self
            numControl.limit.maxMask = "没有足够的库存".loc
            numControl.changeNumValue = {
                wself?.changeGoodsNum(num: $0)
            }
            
        }
        
        @objc func deleteInvalid() {
            mo.model[FK.selected] = true.tag
            active(ID: "deleteInvalidItem", object: mo.model)
        }
        
        
        func changeGoodsNum(num:Int) {
            weak var wself = self
            let optionid = mo.model["optionid",""]
            let id = mo.model["id",""]
            JoTask().post.log._surl(.更改购物车数量).params(["total":num,"optionid":optionid,"id":id]).json_handle { (status, msg, obj, respones) in
                if status.isSuccess{
                    if let dict = obj as? NSMutableDictionary{
                        //                        wself?.numControl.limit.max = dict[int:"total",1]
                        wself?.mo.model[numKey] = num
                        wself?.active(ID: "changeNum", object: dict)
                        return
                    }
                }
                guard let ws = wself else{return}
                let num =  ws.mo.model[int:numKey,1]
                ws.numControl.value = num
                
                msg.alert()
                }.run()
        }
        
        @objc func openDetail(){
            let ctr = Goods.DetailCtrType.init()
            ctr.mo.model = ["id":mo.model["goodsid",""]]
            mo.controller?.navigationController?.pushViewController(ctr, animated: true)
        }
        
        @objc func toggle() {
            if mo.model[FK.selected,"0"] == "1"
            {
                mo.model[FK.selected] = "0"
                //                selectedBt.isSelected =  true
            }
            else
            {
                mo.model[FK.selected] = "1"
                //                selectedBt.isSelected = false
            }
            
            let id = mo.model["id",""]
            weak var wself = self
            JoTask().post.log._surl(.更改购物车选择状态).params(["select":mo.model["selected","0"],"id":id]).json_handle { (status, msg, obj, respones) in
                if status.isSuccess{
                    if let dict = obj as? NSMutableDictionary{
                        wself?.active(ID: "changeSelected", object: dict)
                        return
                    }
                }
                
                
                msg.alert()
                }.run()
            
            self.mo_model_reload()
        }
        
        
        override func mo_model_reload() {
            imgV.img_url = mo.model["thumb",""]
            titleL.text = mo.model["title",""]
            tagsL.text = mo.model["optiontitle",""]
            
            let price = mo.model[float:"marketprice",0]
            
            priceL.attributedText = "¥ ".ui.font11.color(color: ___shop.tint).astring + price.price_display.ui.color(color: ___shop.tint).font12.astring
            numControl.value = mo.model[int:numKey,1]
            
            
            numControl.limit.max = mo.model[int:"stock",1]
            disValidIndicator.alpha = 0
            
            if mo.model["status",false.tag] == true.tag
            {
                numControl.alpha = 1
                contentView.insertSubview(disValidView, belowSubview: selectedBt)
            }
            else{
                numControl.alpha = 0
                disValidIndicator.alpha = 1
                contentView.insertSubview(disValidView, aboveSubview: numControl)
                disValidView.backgroundColor = .color(light: "#fff8", dark: "#ccc2")
            }
            
            if mo.model[FK.selected,"0"] == "1"
            {
                selectedBt.isSelected =  true
            }
            else
            {
                selectedBt.isSelected = false
            }
        }
    }
    
    class NumStepControl:JoView{
        
        weak var controller:UIViewController? = nil
        public var limit = NumLimit()
        public var value:Int = 1
        {
            didSet{
                numT.text = "\(value)"
            }
        }
        
        public var numT = UILabel()
        let addBt = UIButton()
        let reduceBt = UIButton()
        var changeNumValue:(Int) ->Void = {_ in}
        override func addLayoutRules() {
            let numB = UIView()
            self.eelay = [
                [numB,[ee.X],[ee.T.B],24],
                [numT,[ee.X.Y],24],
                [reduceBt,[numT,ee.L,ee.R,-1],[ee.T.L.B],24],
                [addBt,[numT,ee.R,ee.L,1],[ee.T.L.B],24],
            ]
            numT.text = "1"
            numB.backgroundColor = ._background
            numT.textAlignment = .center
            numT.backgroundColor = ._background
            reduceBt.backgroundColor = ._background
            addBt.backgroundColor = ._background
            addBt.ui.font(size: 14).ncolor(color: ._foreground).ntitle(title: "+")
            reduceBt.ui.font(size: 14).ncolor(color: ._foreground).ntitle(title: "-")
            //            self.backgroundColor = UIColor(shex:"#aaa")
            //            self.bsui.set(radius: 0, width: 1, color: UIColor(shex:"#aaa"))
            
            _ = numT.ui.font12.text(color: ._foreground).center
            numT.tintColor = ._tint
            addBt.tag = 1
            reduceBt.tag = -1
            
            addBt.addTarget(self, action: #selector(updateNum(sender:)), for: .touchUpInside)
            reduceBt.addTarget(self, action: #selector(updateNum(sender:)), for: .touchUpInside)
        }
        
        
        
        @objc func updateNum(sender:UIButton) {
            let num = sender.tag
            let newValue = self.value + num
            reduceBt.isEnabled = true
            addBt.isEnabled = true
            if newValue > (limit.max)
            {
                self.limit.maxMask.alert()
                addBt.isEnabled = false
            }
            if newValue < (limit.min)
            {
                reduceBt.isEnabled = false
                //            self.minAlert.alert()
            }
            if (newValue >= limit.min) && (newValue<=limit.max){
                self.value = newValue
                self.changeNumValue(newValue)
            }
            //        self.willSetNewValue(newValue: newValue)
        }
        
        //        @discardableResult
        //        func willSetNewValue(newValue:Int)->Bool {
        //            self.addBt.isEnabled = true
        //            self.reduceBt.isEnabled = true
        //
        //            if newValue > (limit.max)
        //            {
        //                self.limit.maxMask.alert()
        //                self.addBt.isEnabled = false
        //                return false
        //            }
        //            if newValue < (limit.min)
        //            {
        //                reduceBt.isEnabled = false
        //                return false
        //            }
        //            self.value = newValue
        //            if newValue == limit.max
        //            {
        //                addBt.isEnabled = false
        //
        //            }
        //            if newValue == limit.min
        //            {
        //                reduceBt.isEnabled = false
        //            }
        //            return true
        //        }
        override var intrinsicContentSize: CGSize{
            return [72,24]
        }
        
    }
    
}

